class Snake {
    // 获取蛇的信息
    ele: HTMLElement
    // 表示蛇头的元素
    head: HTMLElement
    // 蛇的身体(包括身体)
    bodies: HTMLCollection
    constructor() {
        this.ele = document.querySelector('#snake')!
        this.head = document.querySelector('#snake>div')!
        this.bodies = this.ele.getElementsByTagName('div')
    }

    // 获取蛇的坐标
    public get X(): number {
        return this.head.offsetLeft
    }
    public get Y(): number {
        return this.head.offsetTop
    }


    // 设置蛇头的坐标
    public set X(v: number) {
        // 如果新值和旧值相当，则直接返回
        if (this.X == v) {
            return
        }
        // X值的返回
        if (v < 0 || v > 290) {
            throw new Error('重开吧你,太菜了')
        }
        // 修改X时，在修改水平坐标，射在左右移动，不能让它掉头
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft == v) {
            // console.log('水平方向发生了掉头');
            // 发生掉头，让蛇反方向继续移动
            if (v > this.X) {
                v = this.X - 10
            } else {
                v = this.X + 10
            }
        }
        // 移动身体
        this.moveBody()
        this.head.style.left = v + 'px';
        this.cheackHeadBody()
    }


    public set Y(v: number) {
        if (this.Y == v) {
            return
        }
        if (v < 0 || v > 290) {
            throw new Error('重开吧你,太菜了')
        }
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop == v) {
            // console.log('水平方向发生了掉头');
            // 发生掉头，让蛇反方向继续移动
            if (v > this.Y) {
                v = this.Y - 10
            } else {
                v = this.Y + 10
            }
        } 
        this.moveBody()
        this.head.style.top = v + 'px';
        this.cheackHeadBody()
    }


    // 蛇添加身体
    addBody() {
        // 向ele添加一个div   insetAdjacentHTML尾部
        // console.log(this.bodies.length);
        this.ele.insertAdjacentHTML("beforeend", "<div></div>")
    }
    moveBody() {
        // console.log(this.bodies.length);

        for (let i = this.bodies.length - 1; i > 0; i--) {
            // 获取前边身体的位置
            let X = (this.bodies[i - 1] as HTMLElement).offsetLeft;
            let Y = (this.bodies[i - 1] as HTMLElement).offsetTop;
            // 将这个值设置到当前的身体上
            (this.bodies[i] as HTMLElement).style.left = X + 'px';
            (this.bodies[i] as HTMLElement).style.top = Y + 'px'
        }
    }
    cheackHeadBody(){
        for(let i =1;i<this.bodies.length;i++){
            let bd =this.bodies[i] as HTMLElement
            if (this.X == (bd.offsetLeft) && this.Y==(bd.offsetTop)) {
                // 撞到身体游戏结束
                throw new Error('自己撞自己,不错技术非常好')
            }
        }
    }
}

export default Snake